package com.example.xposedtest.xposed;

import android.app.Application;
import android.content.ContentValues;
import android.content.Context;
import android.util.Log;

import com.example.xposedtest.network.DeepSeekApiClient;
import com.example.xposedtest.wechat.WeChatMessageSender;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

public class WeChat implements IXposedHookLoadPackage {
    private static final String TAG = "Xposed-Debug";
    private static final String WECHAT_PACKAGE = "com.tencent.mm";
    private static final String MODULE_PACKAGE = "com.example.xposedtest";
    private static final String PREFS_NAME = "XposedPrefs";

    // 配置键名（与MainActivity对应）
    private static final String PREF_AUTO_REPLY = "auto_reply_enabled";
    private static final String PREF_REPLY_TYPE = "reply_type"; // 0:DeepSeek 1:自定义文本 2:图片 3:视频
    private static final String PREF_CUSTOM_TEXT = "custom_text";
    private static final String PREF_IMAGE_PATH = "image_path";
    private static final String PREF_VIDEO_PATH = "video_path";

    private DeepSeekApiClient deepSeekClient;
    private Context wxContext;
    private XSharedPreferences prefs;
    private WeChatMessageSender messageSender;
    private static final boolean DEBUG_THROW_EXCEPTION = false;

    @Override
    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
        if (lpparam.packageName.equals(WECHAT_PACKAGE)) {
            Log.e(TAG, "检测到微信加载: " + lpparam.packageName);
            deepSeekClient = new DeepSeekApiClient(); // 确保DeepSeekApiClient已实现

            // 初始化XSharedPreferences（读取MainActivity配置）
            prefs = new XSharedPreferences(MODULE_PACKAGE, PREFS_NAME);
            prefs.makeWorldReadable();

            // Hook微信应用初始化，获取上下文和类加载器（关键：用Tinker类加载器）
            XposedHelpers.findAndHookMethod("com.tencent.tinker.loader.app.TinkerApplication",
                    lpparam.classLoader, "attachBaseContext", Context.class,
                    new XC_MethodHook() {
                        @Override
                        protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                            Log.e(WeChat.TAG, "Hook到微信应用初始化");
                            Application application = (Application) param.thisObject;
                            wxContext = application.getBaseContext();
                            ClassLoader tinkerClassLoader = application.getClassLoader(); // 微信Tinker类加载器

                            // 初始化消息发送器（传入Tinker类加载器）
                            messageSender = new WeChatMessageSender(wxContext, tinkerClassLoader);

                            // 执行后续Hook逻辑
                            WeChat.this.setClassloaderAndExecuteHook(tinkerClassLoader);
                        }
                    });
        }

        // 注册步数修改Hook
        StepHook.hook(lpparam);
    }

    public void setClassloaderAndExecuteHook(ClassLoader classLoader) {
        // Hook微信消息数据库插入（监听收发消息）
        XposedHelpers.findAndHookMethod("com.tencent.wcdb.database.SQLiteDatabase", classLoader,
                "insertWithOnConflict",
                String.class, String.class, ContentValues.class, Integer.TYPE,
                new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        // 每次读取最新配置
                        prefs.reload();

                        String table = (String) param.args[0];
                        ContentValues values = (ContentValues) param.args[2];

                        // 1. 检查总开关是否开启
                        boolean isAutoReplyEnabled = prefs.getBoolean(PREF_AUTO_REPLY, false);
                        if (!isAutoReplyEnabled) {
                            Log.d(TAG, "自动回复总开关已关闭，跳过处理");
                            return;
                        }

                        // 2. 只处理消息主表（message/message2）
                        if (!"message".equals(table) && !"message2".equals(table)) {
                            return;
                        }

                        // 3. 区分收发消息（is_send=0：收到消息；1：发出消息）
                        Integer isSend = values.getAsInteger("is_send");
                        if (isSend == null) isSend = values.getAsInteger("isSend"); // 兼容不同微信版本
                        if (isSend == null || isSend == 1) { // 只处理"收到的消息"
                            return;
                        }

                        // 4. 提取目标微信ID（消息发送者，即回复对象）
                        String targetWxId = values.getAsString("talker");
                        String receivedContent = values.getAsString("content");
                        if (targetWxId == null || targetWxId.isEmpty()) {
                            Log.w(TAG, "目标微信ID为空，跳过回复");
                            return;
                        }
                        Log.d(TAG, "收到消息（来自: " + targetWxId + "）: " + (receivedContent == null ? "无内容" : receivedContent));

                        // 5. 异步执行自动回复（避免阻塞微信主线程）
                        new Thread(() -> {
                            try {
                                // 5.1 读取当前回复类型
                                int replyType = prefs.getInt(PREF_REPLY_TYPE, 0);
                                Log.d(TAG, "当前回复类型：" + replyType);

                                // 5.2 根据类型分支处理
                                switch (replyType) {
                                    case 0: // DeepSeek生成文本
                                        handleDeepSeekReply(targetWxId, receivedContent);
                                        break;
                                    case 1: // 自定义文本
                                        handleCustomTextReply(targetWxId);
                                        break;
                                    case 2: // 图片回复（核心：调用改造后的sendImageMessage）
                                        handleImageReply(targetWxId);
                                        break;
                                    case 3: // 视频回复（待改造，参考图片逻辑）
                                        handleVideoReply(targetWxId);
                                        break;
                                    default:
                                        Log.w(TAG, "未知回复类型：" + replyType);
                                }

                                if (DEBUG_THROW_EXCEPTION) {
                                    throw new Exception("[调试] 回复完成，目标: " + targetWxId + ", 类型: " + replyType);
                                }

                            } catch (Exception e) {
                                Log.e(TAG, "自动回复流程异常", e);
                            }
                        }).start();
                    }
                });

        // 保留原有st0.t0构造函数Hook（调试用）
        hookSt0t0Constructors(classLoader);
        Log.i(TAG, "微信Hook初始化完成");
    }

    // 处理DeepSeek生成文本回复（保留原有逻辑）
    private void handleDeepSeekReply(String targetWxId, String receivedContent) {
        try {
            if (receivedContent == null || receivedContent.isEmpty()) {
                Log.w(TAG, "收到消息为空，跳过DeepSeek回复");
                return;
            }

            String deepSeekReply = deepSeekClient.getReply(receivedContent);
            if (deepSeekReply == null || deepSeekReply.trim().isEmpty()) {
                Log.w(TAG, "DeepSeek生成回复为空");
                return;
            }

            boolean success = messageSender.sendTextMessage(targetWxId, deepSeekReply);
            Log.d(TAG, "DeepSeek回复发送" + (success ? "成功" : "失败") + "：" + deepSeekReply);
        } catch (Exception e) {
            Log.e(TAG, "DeepSeek回复处理失败", e);
        }
    }

    // 处理自定义文本回复（保留原有逻辑）
    private void handleCustomTextReply(String targetWxId) {
        try {
            String customText = prefs.getString(PREF_CUSTOM_TEXT, "");
            if (customText.isEmpty()) {
                Log.w(TAG, "自定义文本为空，跳过回复");
                return;
            }

            boolean success = messageSender.sendTextMessage(targetWxId, customText);
            Log.d(TAG, "自定义文本回复发送" + (success ? "成功" : "失败") + "：" + customText);
        } catch (Exception e) {
            Log.e(TAG, "自定义文本回复处理失败", e);
        }
    }

    // 处理图片回复（调用改造后的发送方法）
    private void handleImageReply(String targetWxId) {
        try {
            String imagePath = prefs.getString(PREF_IMAGE_PATH, "");
            if (imagePath.isEmpty()) {
                Log.w(TAG, "图片路径为空，跳过回复");
                return;
            }

            // 调用改造后的sendImageMessage
            boolean success = messageSender.sendImageMessage(targetWxId, imagePath);
            Log.d(TAG, "图片回复发送" + (success ? "成功" : "失败") + "：" + imagePath);
        } catch (Exception e) {
            Log.e(TAG, "图片回复处理失败", e);
        }
    }

    // 处理视频回复（待改造，参考图片逻辑）
    private void handleVideoReply(String targetWxId) {
        try {
            String videoPath = prefs.getString(PREF_VIDEO_PATH, "");
            if (videoPath.isEmpty()) {
                Log.w(TAG, "视频路径为空，跳过回复");
                return;
            }

            boolean success = messageSender.sendVideoMessage(targetWxId, videoPath);
            Log.d(TAG, "视频回复发送" + (success ? "成功" : "失败") + "：" + videoPath);
        } catch (Exception e) {
            Log.e(TAG, "视频回复处理失败", e);
        }
    }

    // 保留原有st0.t0构造函数Hook（调试用）
    private void hookSt0t0Constructors(ClassLoader classLoader) {
        try {
            // 构造1：String, String, int, int, long
            XposedHelpers.findAndHookConstructor("st0.t0", classLoader,
                    String.class, String.class, int.class, int.class, long.class,
                    new XC_MethodHook() {
                        @Override
                        protected void beforeHookedMethod(MethodHookParam param) {
                            Log.d(TAG, "st0.t0构造1 - p0: " + param.args[0] + ", p1: " + param.args[1] +
                                    ", p2: " + param.args[2] + ", p3: " + param.args[3] + ", p4: " + param.args[4]);
                        }
                    });

            // 构造2：String, String, int, int, Object
            XposedHelpers.findAndHookConstructor("st0.t0", classLoader,
                    String.class, String.class, int.class, int.class, Object.class,
                    new XC_MethodHook() {
                        @Override
                        protected void beforeHookedMethod(MethodHookParam param) {
                            Log.d(TAG, "st0.t0构造2 - p0: " + param.args[0] + ", p1: " + param.args[1] +
                                    ", p2: " + param.args[2] + ", p3: " + param.args[3] + ", p4: " + param.args[4]);
                        }
                    });

        } catch (Exception e) {
            Log.e(TAG, "Hook st0.t0构造函数失败", e);
        }
    }


}